/*
 * @Description: 单向队列
 * @Autor: wangxin
 * @Date: 2020-06-09 14:48:44
 * @LastEditors: Seven
 * @LastEditTime: 2020-06-10 08:53:36
 */
class Queue {
  constructor() {
    this.count = 0 // 队列长度
    this.lowestCount = 0 // 用于追踪第一个元素
    this.items = {}
  }

  /* 前端添加元素 */
  enqueue(element) {
    this.items[this.count] = element
    this.count++
  }

  /* 删除第一个元素 */
  dequeue() {
    if (this.isEmpty()) {
      return undefined
    }
    const result = this.items[this.lowestCount]
    delete this.items[this.lowestCount]
    this.lowestCount++
    return result
  }

  isEmpty() {
    return this.count === 0
  }

  /* 返回第一个元素 */
  peek() {
    if (this.isEmpty()) {
      return undefined
    }
    return this.items[this.lowestCount]
  }

  size() {
    return this.count - this.lowestCount
  }

  clear() {
    this.count = 0
    this.lowestCount = 0
    this.items = {}
  }

  toString() {
    if (this.isEmpty()) {
      return ''
    }
    let str = `${this.items[this.lowestCount]}`
    for (let i = this.lowestCount + 1; i < this.count; i++) {
      str = `${str},${this.items[i]}`
    }
    return str
  }
}
// 测试代码
// var queue = new Queue()
// queue.enqueue(1)
// queue.enqueue(2)
// queue.enqueue(3)
